<?php

/*
 * Выводит sitemap в xml формате
 *
 */


function buildXmlNode (&$treeDump, &$xml = null, $prevName = '', &$baseURL) {
	$prevName = $prevName == ""?"":$prevName.="/";
	foreach ($treeDump as $n => $page) {
		$currentName = $prevName.rawurlencode($page['name']);
		if (isset($page['children']) && is_array($page['children'])) {
			buildXmlNode ($page['children'], $xml, $currentName, $baseURL);
		} else {
			if ($page['name'] != 'index' && $page['name'] != 'sitemap') {
				if ($page['in_menu']=='true' && $page['active']=='true') {
					$xml->addChild ('url')->addChild ('loc', $baseURL.$currentName);
				}
			}
		}
	}
}

function produceSiteMap (&$db, &$TREE, &$tree_params, &$name_fields, &$baseURL) {
	$treeDump = $TREE->_dump(0, $name_fields, true);
	$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>');
	//$urlXML = $xml->addChild ('url');
	buildXmlNode ($treeDump, $xml, '', $baseURL);
	print $xml->asXML();
}

function smarty_function_sitemap ($params, $template)
{

	require_once BASEPATH.'core/Model'.EXT;
	require_once BASEPATH.'core/CodeIgniter'.EXT;
	include_once APPPATH."/libraries/Treeclass.php";

	$tree_params = array (
		'table'		=> 'foria_pages',
		'id_node_name' => 'page',
		'id'		=> 'id',
		'parent_id'	=> 'parent_id',
		'position'	=> 'position',
		'level'		=> 'level'
	);

	$name_fields = array (
		'name',
		'active',
		'in_menu'
	);

	$TREE = new Treeclass ($tree_params);

	$baseURL = site_url("");

	produceSiteMap ($db, $TREE, $tree_params, $name_fields, $baseURL);

	return "";

}
